package fr.univ.surveyonline.question.xmlbuilder;

import java.io.CharArrayReader;
import java.io.IOException;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import fr.univ.surveyonline.question.FormField;

public class FormFieldBuilder {

	public static String suppressInutileBalise(String xml2) {
		if (xml2.equalsIgnoreCase("<formfield/>")) {
			xml2 = "<formfield></formfield>";
		}
		StringBuffer res = new StringBuffer("");
		StringBuffer xml = new StringBuffer(xml2);
		while (xml.length() > 0) {
			if ((xml.charAt(0) == '/')&&(xml.charAt(1) == '>')) {
				xml.deleteCharAt(0);
				xml.deleteCharAt(0);
				int i = res.length() -1;
				while (res.charAt(i) != '<') {
					res.deleteCharAt(i);
					i--;
				}
				res.deleteCharAt(i);
			} else {
				res.append(xml.charAt(0));
				xml.deleteCharAt(0);
			}
		}
		return res.toString();
	}
	
	public static String getXmlFromSurvey(FormField f)	{
		return FormFieldToXML.fromFormFieldToXML(f);
	}
	
	public static FormField getSurveyFromXML(String xml) throws IOException, SAXException {
		XMLReader saxReader = XMLReaderFactory.createXMLReader();
		FormFieldParser fb = new FormFieldParser();
		saxReader.setContentHandler(fb);

		int leng = xml.length();
		char[] cbuf = new char[leng];
		for (int i=0; i < leng;i++) {
			cbuf[i] = xml.charAt(i);
		}
		
		InputSource i = new InputSource(new CharArrayReader(cbuf));
		
		saxReader.parse(i);
		
		FormField f = fb.getSurvey();
		if (f == null) {
			throw new IllegalStateException("Erreur");
		}
		return f;
	}
	
	public static FormField createSurveyFromExistingSurvey(FormField f) throws IOException, SAXException {
		return transformKey.transform_key(f);
	}	
}
